﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using NReader.Model.RAS;
using NReader.Service;
using Windows.Data.Html;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using XnReader.WinRT.Common;
using XnReader.WinRT.Controlx;
using XnReader.WinRT.Forms;

// “项目页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234233 上提供

namespace XnReader.WinRT
{
    /// <summary>
    /// 显示项预览集合的页。在“拆分布局应用程序”中，此页
    /// 用于显示及选择可用组之一。
    /// </summary>
    public sealed partial class Book
    {
        private IList<ChapterInfo> _maxChapters;

        private ArticleInfo _article;

        public Book()
        {
            InitializeComponent();
            var visiblesFooter = new CommandInfo
            {
                Theme = "white",
                VisibleSearch = Visibility.Visible,
                VisibleAddBookcase = Visibility.Visible,
                VisibleBookcase = Visibility.Visible
            };
            if (tlBottom != null)
            {
                tlBottom.DataContext = visiblesFooter;
                tlBottom.AddBookcaseClickEvent += BtnAddBookStoreClick;
            }
        }

        #region ?san 由于选中样式未改变，取消右键跳转目录

        //void TlBottomBookReaderClickEvent(object sender, RoutedEventArgs e)
        //{
        //    var selectedItems = itemGridView.SelectedItems;
        //    if (selectedItems != null && selectedItems.Count > 0)
        //    {
        //        var chapter = selectedItems[0] as ChapterInfo;
        //        var tran = new BookTranChapterInfo { CurrentChapter = chapter };
        //        if (_maxChapters != null) 
        //            tran.MaxChapters = _maxChapters;

        //        Frame.Navigate(typeof(BookReader), tran);
        //    }
        //}

        //private void ItemGridViewSelectionChanged(object sender, SelectionChangedEventArgs e)
        //{
        //    BottomAppBar.IsOpen = itemGridView.SelectedItems.Count > 0;
        //}

        #endregion

        /// <summary>
        /// 使用在导航过程中传递的内容填充页。在从以前的会话
        /// 重新创建页时，也会提供任何已保存状态。
        /// </summary>
        /// <param name="navigationParameter">最初请求此页时传递给
        /// <see cref="Frame.Navigate(Type, Object)"/> 的参数值。
        /// </param>
        /// <param name="pageState">此页在以前会话期间保留的状态
        /// 字典。首次访问页面时为 null。</param>
        protected override async void LoadState(Object navigationParameter, Dictionary<string, object> pageState)
        {
            var articleid = (int) navigationParameter;
            //从挂起恢复的操作
            if ((pageState != null
                 && pageState.ContainsKey("Page")
                 && pageState["Page"].ToString().Equals("Book")))
                //|| await Helper.GlobalUtils.CheckConnectionState() == false)
            {
                _article = await ArticleService.Instance().GetArticle(articleid);
                _article.intro = HtmlUtilities.ConvertToText(_article.intro);//将简介转换成HTML
                DefaultViewModel["Article"] = _article;

                _maxChapters = await ChapterService.GetMaxChaptersLocal(articleid);
                cvs2.Source = _maxChapters;
            }
            else //从导航的操作
            {
                _article = await ArticleService.Instance().GetArticle(articleid);
                _article.online = 1;
                if (_article != null)
                {
                    DefaultViewModel["Article"] = _article;
                    _maxChapters = await ArticleService.Instance().GetMaxChapterList(articleid);
                    cvs2.Source = _maxChapters;
                    pbLoading.IsActive = false;
                    await Task.Run(() => SaveBook());
                }
            }
            if (_article != null && !String.IsNullOrEmpty(_article.coverlink) &&
                itemGridView.Visibility == Visibility.Visible)
            {
                await DataBindingCover(_article.coverlink);
            }
            pbLoading.IsActive = false;
        }

        /// <summary>
        /// 保留与此页关联的状态，以防挂起应用程序或
        /// 从导航缓存中放弃此页。值必须符合
        /// <see cref="SuspensionManager.SessionState"/> 的序列化要求。
        /// </summary>
        /// <param name="pageState">要使用可序列化状态填充的空字典。</param>
        protected override void SaveState(Dictionary<string, object> pageState)
        {
            pageState["Page"] = "Book";
        }

        /// <summary>
        /// 保存书籍信息
        /// </summary>
        /// <returns></returns>
        private async Task SaveBook()
        {
            if (_article != null)
            {
                //添加到SQLITE
                if (await ArticleService.Instance().AddBook(_article))
                {
                    //保存最大章节到文件
                    if (_maxChapters != null)
                    {
                        await ChapterService.SaveMaxChapters(_article.articleid, _maxChapters);
                    }
                }
            }
        }

        /// <summary>
        /// 绑定封面
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public async Task DataBindingCover(string url)
        {
            var cover = await ArticleService.Instance().GetCover(_article.articleid);
            if (cover == null)
            {
                try
                {
                    var client = new HttpClient();
                    HttpResponseMessage response = await client.GetAsync(url);
                    response.EnsureSuccessStatusCode();
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                    cover = await ArticleService.Instance().SaveCover(_article.articleid,
                                await response.Content.ReadAsByteArrayAsync());
                    }
                }
                catch (Exception)
                {

                }
   
            }
            if (cover != null)
            {
                imgCover.Source = cover;
            }
        }

        /// <summary>
        /// 添加书架
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void BtnAddBookStoreClick(object sender, RoutedEventArgs e)
        {
            if (_article != null)
            {
                _article.updatetime = DateTime.Now.ToString("yyyyMMddHHmmss");
                var article = await ArticleService.Instance().GetArticleFormLocal(_article.articleid);
                string tips;
                if (article != null)
                {
                    tips = "该书已经在您的书架上！";
                }
                else if (await ArticleService.Instance().GetBookStoreCountFromLocal(1) > 30)
                {
                    tips = "您书架的数目已经超过上限30本！";
                }
                else
                {
                    var result = await ArticleService.Instance().AddBookStoreToLocal(_article.articleid,1);
                    tips = result ? "添加书架成功！" : "添加书架失败，请稍后重试！";
                }
                var md = new MessageDialog(tips);
                await md.ShowAsync();
            }
        }

        /// <summary>
        /// 点击GRIDVIEW导航到CHAPTER
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void ItemGridViewItemClick(object sender, ItemClickEventArgs e)
        {
            if (e.ClickedItem != null)
            {
                var chapter = ((ChapterInfo) e.ClickedItem);
                await ChapterService.SaveChapterSession(chapter);
                //Frame.Navigate(typeof (Chapter), chapter.chapterid);
                var param = string.Format("{0}|{1}|{2}|{3}|{4}|current|{5}", "online",
                                          chapter.articleid,
                                          chapter.articlename,
                                          "", //item.articletype,
                                          0, //chapter.historyprogress,
                                          chapter.chapterid); //chapter.historychapterid)

                Frame.Navigate(typeof (ChapterIndex), param);
            }
        }
    }
}